package mongox

import (
	"fmt"
	"sync"

	"go.mongodb.org/mongo-driver/bson/primitive"
)

var (
	_idMutex sync.Mutex
)

func GetId() primitive.ObjectID {
	_idMutex.Lock()
	defer _idMutex.Unlock()
	return primitive.NewObjectID()
}

func GetIds(n int) []primitive.ObjectID {
	_idMutex.Lock()
	defer _idMutex.Unlock()
	ids := make([]primitive.ObjectID, 0, n)
	for i := 0; i < n; i++ {
		ids = append(ids, primitive.NewObjectID())
	}
	return ids
}

func ConvertIds(ids []string) (oids []primitive.ObjectID, err error) {
	oids = make([]primitive.ObjectID, 0, len(ids))
	for _, id := range ids {
		oid, err := primitive.ObjectIDFromHex(id)
		if err != nil {
			return nil, fmt.Errorf("invalid id: %s", id)
		}
		oids = append(oids, oid)
	}
	return oids, nil
}
